package edu.whut.controller;

import edu.whut.entity.CommonResult;
import edu.whut.entity.User;
import edu.whut.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    /***
     * 功能：注册（添加）用户
     * @param user
     * @return 响应信息
     */
    @RequestMapping("/register")
    public CommonResult register(@RequestBody User user) {
        if(userService.getUserByPhone(user.getPhone())!=null){
            return new CommonResult(400,"请输入正确的账号和密码",null);
        }
        if (userService.addUser(user)) {
            return new CommonResult(200, "add a new user", user);
        }
        return new CommonResult(400, "请输入正确的账号和密码", null);
    }

    /***
     * 功能：删除用户
     * @param userId
     * @return 响应信息
     */
    @RequestMapping("/delete")
    public CommonResult deleteUser(@RequestParam("userId") Long userId) {
        if (userService.deleteUser(userId)) {
            return new CommonResult(200, "delete this user", null);
        }
        return new CommonResult(400, "error", null);
    }

    /***
     * 功能: 用户信息的修改
     * @param user
     * @return 响应信息
     */
    @RequestMapping("/update")
    public CommonResult updateUser(@RequestBody User user) {
        if (userService.updateUser(user)) {
            return new CommonResult(200, "successfully update user", null);
        }
        return new CommonResult(400, "error", null);
    }

    @RequestMapping("/get")
    public CommonResult getUser(@RequestParam("userId") Long userId) {
        User user = userService.getUser(userId);
        if (user != null) {
            return new CommonResult(200, "success", user);
        }
        return new CommonResult(400, "not found", null);
    }

    /***
     * 调用userService中的login函数，通过用户名和密码，判断是否能登录成功，并返回相应的响应
     * @param username
     * @param password
     * @return 响应信息
     */
    @RequestMapping("/login")
    public CommonResult<User> login(@RequestParam("phone") Long phone,
                              @RequestParam("password") String password) {
        if (userService.login(phone, password)) {
            return new CommonResult<>(200, "login success", userService.getUserByPhone(phone));
        }
        return new CommonResult<>(400, "请输入正确的账号和密码", null);
    }
}
